<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>商品管理</el-breadcrumb-item>
  <el-breadcrumb-item>分类参数</el-breadcrumb-item>
</el-breadcrumb>
<!-- 卡片视图区域 -->
<el-card>
  <!-- 警告区域 -->
   <el-alert
    title="注意：只允许为第三级分类设置相关参数！"
    type="warning"
    show-icon
    :closable="false">
  </el-alert>
  <!-- 商品分类选择区域 -->
  <el-row>
    <el-col>选择商品分类：
       <el-cascader
    v-model="selectCateId"
    :options="goodsList"
    :props="cateCnfigObj"
    @change="optionsChange"  size="mini"></el-cascader>
    </el-col>
  </el-row>
  <!-- 标签页切换区域 -->
   <el-tabs v-model="activeName" @tab-click="handleClick">
    <el-tab-pane label="动态参数" name="many">
      <el-button type="primary" :disabled="isOpen" size="mini" @click="addManyDialogVisible = true">添加参数</el-button>
      <!-- 动态参数表格数据 -->
       <el-table
      :data="manyTableData"
      style="width: 100%"
      border stripe>
      <el-table-column  type="expand">
        <template slot-scope="scope">
          <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable disable-transitions @close="deleteTag(scope.row,i)">{{item}}</el-tag>
          <el-input
          class="input-new-tag"
          v-if="scope.row.inputVisible"
          v-model="scope.row.inputValue"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleInputConfirm(scope.row)"
          @blur="handleInputConfirm(scope.row)">
          </el-input>
<el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
        </template>
      </el-table-column>
      <el-table-column type="index" label="#"></el-table-column>
      <el-table-column
        prop="attr_name"
        label="参数名称"
        >
      </el-table-column>
      <el-table-column
        label="操作"
        >
        <template slot-scope="scope">
         <el-button type="primary" icon="el-icon-edit" size="mini" @click="modifyForm(scope.row)">修改</el-button>
         <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParamOption(scope.row)">删除</el-button>
        </template>
      </el-table-column>
       </el-table>
    </el-tab-pane>
    <el-tab-pane label="静态属性" name="only">
      <el-button type="primary" :disabled="isOpen" size="mini" @click="addOnlyDialogVisible = true">添加属性</el-button>
       <!-- 静态参数表格数据 -->
       <el-table
      :data="onlyTableData"
      style="width: 100%"
      border stripe>
      <el-table-column  type="expand">
        <template slot-scope="scope">
          <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable disable-transitions @close="deleteTag(scope.row,i)">{{item}}</el-tag>
          <el-input
          class="input-new-tag"
          v-if="scope.row.inputVisible"
          v-model="scope.row.inputValue"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleInputConfirm(scope.row)"
          @blur="handleInputConfirm(scope.row)">
          </el-input>
<el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
        </template>
      </el-table-column>
      <el-table-column type="index" label="#"></el-table-column>
      <el-table-column
        prop="attr_name"
        label="属性名称"
        >
      </el-table-column>
      <el-table-column
        label="操作"
        >
        <template slot-scope="scope">
         <el-button type="primary" icon="el-icon-edit" size="mini" @click="modifyForm(scope.row)">修改</el-button>
         <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParamOption(scope.row)">删除</el-button>
        </template>
      </el-table-column>
       </el-table>
    </el-tab-pane>
  </el-tabs>
  <!-- 标签页切换区域结束 -->
</el-card>
<!-- 添加动态参数对话框 -->
  <el-dialog
  title="添加动态参数"
  :visible.sync="addManyDialogVisible"
  width="50%"
  @closed="clearCheckManyRule"
  >
  <!-- 添加动态属性表单区域 -->
  <el-form :model="addManyForm" :rules="addManyFormRules" ref="addManyFormRef" label-width="100px">
  <el-form-item label="动态参数：" prop="attr_name">
    <el-input v-model="addManyForm.attr_name"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addManyDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addManyDataConfirm">确 定</el-button>
  </span>
</el-dialog>
<!-- 添加静态属性对话框 -->
  <el-dialog
  title="添加静态属性"
  :visible.sync="addOnlyDialogVisible"
  width="50%"
  @closed="clearCheckOnlyRule"
  >
  <!-- 添加静态属性表单区域 -->
  <el-form :model="addOnlyForm" :rules="addOnlyFormRules" ref="addOnlyFormRef" label-width="100px">
  <el-form-item label="静态属性：" prop="attr_name">
    <el-input v-model="addOnlyForm.attr_name"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addOnlyDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addOnlyDataConfirm">确 定</el-button>
  </span>
</el-dialog>
<!-- 修改表单对话框区域 -->
<el-dialog
  :title="'修改'+titleText"
  :visible.sync="modifyDialogVisible"
  width="50%"
  @closed="resetModifyCheckRules">
  <!-- 修改表单区域 -->
  <el-form :model="modify_Form" :rules="modifyFormRules" ref="modifyFormRef" label-width="100px">
  <el-form-item :label="titleText" prop="attr_name">
    <el-input v-model="modify_Form.attr_name"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="modifyDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="modifyFormConfirm">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 商品分类列表数据
      goodsList: [],
      cateCnfigObj: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择的每一项的id一次存储在数组里面
      selectCateId: [],
      // 标签页数据绑定
      activeName: 'many',
      // 控制按钮是否禁用
      isOpen: true,
      // 动态参数数据
      manyTableData: [],
      // 静态参数数据
      onlyTableData: [],
      // 控制添加动态参数对话框的显示与隐藏
      addManyDialogVisible: false,
      // 控制添加静态属性对话框的显示与隐藏
      addOnlyDialogVisible: false,
      // 控制修改对话框的显示与隐藏
      modifyDialogVisible: false,
      // 添加的动态参数表单数据
      addManyForm: {
        attr_name: ''
      },
      // 添加静态属性表单数据
      addOnlyForm: {
        attr_name: ''
      },
      modify_Form: {},
      // 添加动态参数表单验证规则
      addManyFormRules: {
        attr_name: [
          { required: true, message: '请输入动态参数名称', trigger: 'blur' }
        ]
      },
      // 添加动态参数表单验证规则
      addOnlyFormRules: {
        attr_name: [
          { required: true, message: '请输入静态属性名称', trigger: 'blur' }
        ]
      },
      // 通过作用域插槽获取编辑对话框的输入框的内容
      attr_name: '',
      // 修改表单验证规则
      modifyFormRules: {
        attr_name: [
          { required: true, message: `请输入${this.titleText}`, trigger: 'blur' }
        ]
      },
      // 修改请求参数
      attr_id: ''
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories', { params: { type: 3 } })
      if (res.meta.status !== 200) return this.$message.error('获取分类列表失败')
      this.goodsList = res.data
    },
    // 级联选择框发生改变时触发
    async optionsChange() {
      // 控制级联选择器的选中范围
      // 如果选择分类的id数组长度不等于3，则说明选择的不是三级分类
      if (this.selectCateId.length !== 3) {
        this.selectCateId = []
        this.isOpen = true // 禁用按钮
        this.manyTableData = []
        this.onlyTableData = []
        this.getParamsData()
        return
      }
      this.isOpen = false // 打开按钮
      this.getParamsData()
    },
    // 切换标签页触发
    handleClick() {
      this.getParamsData()
    },
    // 获取商品参数数据
    async getParamsData() {
      // 在选择三级分类时发送请求获取动态属性
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return
      // 在给表格数据源赋值前，要对获取到的参数列表中的attr_vals分割成数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 防止每一行都共用一个输入框和控制输入框显示与隐藏的bool值，所以
        // 循环给每一行都加一个独立的输入框和bool值
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(res.data)
      // 因为根据请求参数sel的不同，分别得到动态参数和静态属性两种数据，所以应该分别存储
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 点击确定按钮发送请求，添加动态参数
    addManyDataConfirm() {
    // 发送请求前要进行表单预验证
      this.$refs.addManyFormRef.validate(async boo => {
        if (!boo) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addManyForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('添加失败！')
        this.getParamsData()
        this.$message.success('添加成功！')
        this.addManyDialogVisible = false
      })
    },
    // 点击确定按钮发送请求，添加动态参数
    addOnlyDataConfirm() {
    // 发送请求前要进行表单预验证
      this.$refs.addOnlyFormRef.validate(async boo => {
        if (!boo) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addOnlyForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('添加失败！')
        this.getParamsData()
        this.$message.success('添加成功！')
        this.addOnlyDialogVisible = false
      })
    },
    // 关闭对话框，清除校验规则
    clearCheckManyRule() {
      this.$refs.addManyFormRef.resetFields()
    },
    // 关闭对话框，清除校验规则
    clearCheckOnlyRule() {
      this.$refs.addOnlyFormRef.resetFields()
    },
    // 点击编辑修改表单
    modifyForm(scope) {
      // 使用作用于插槽获取当前编辑项的参数名称
      this.modify_Form = scope
      this.modifyDialogVisible = true
    },
    // 关闭修改对话框时清除校验规则
    resetModifyCheckRules() {
      this.$refs.modifyFormRef.resetFields()
    },
    // 发送修改请求前进行表单验证
    modifyFormConfirm(row) {
      this.$refs.modifyFormRef.validate(async boo => {
        if (!boo) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.modify_Form.attr_id}`, {
          attr_name: this.modify_Form.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) {
          return this.$message.error('修改失败！')
        }
        this.getParamsData()
        this.modifyDialogVisible = false
        this.$message.success('修改成功！')
      })
    },
    // 打开删除确认对话框
    async deleteParamOption(scope) {
      const result = await this.$confirm('此操作将永久删除该条目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => { return err })
      console.log(result)
      if (result === 'cancel') return this.$message.info('已取消删除')
      // 如果点击确认则发送请求删除
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${scope.attr_id}`)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.getParamsData()
      this.$message.success('删除成功')
    },
    // 点击或按下回车触发
    async handleInputConfirm(row) {
      row.inputVisible = false
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        return
      }
      // 如果输入内容不是空字符,将输入内容添加到attr_vals数组中
      row.attr_vals.push(row.inputValue)
      // 同时清空输入框内容
      row.inputValue = ''
      // 发送请求保存修改的参数
      this.saveTags(row)
    },
    // 保存tag标签
    async saveTags(row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('修改失败！')
      this.$message.success('修改成功！')
      console.log(res)
      row.inputVisible = false
    },
    // 显示输入框
    showInput(row) {
      row.inputVisible = true
      // 点击自动获取焦点
      // $nextTick这个函数是等待页面上的元素渲染完成后才会触发，
      // 因为在设置bool值为true是，输入框并不会立即被渲染出来
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除tag标签
    deleteTag(row, i) {
      // 点击删除按钮，在attr_vals数组里删除当前标签
      row.attr_vals.splice(i, 1)
      this.saveTags(row)
    }
  },
  // 使用计算属性设置请求参数：分类id就是级联选择框的三级选项的selectCateId数组的最后一个值
  computed: {
    cateId: function() {
      return this.selectCateId.length === 3 ? this.selectCateId[this.selectCateId.length - 1] : null
    },
    titleText() {
      return this.activeName === 'many' ? '动态参数' : '静态属性'
    }
  }
}
</script>
<style lang="less" scoped>
.el-row{
  margin-top: 20px;
}
.el-tag{
  margin-right: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
